package chineseholiday.infrastructure.holiday;

import chineseholiday.domain.holiday.Holiday;
import chineseholiday.domain.holiday.HolidayGateWay;
import chineseholiday.infrastructure.cache.HolidayCache;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;

/**
 * @author 陈浩
 * @date 2021/5/18 17:14
 */
public class HolidayGateWayImpl implements HolidayGateWay {

    private HashMap<LocalDate, Holiday> cache;

    public HolidayGateWayImpl() throws Exception {
        cache = HolidayCache.getCache();
    }


    @Override
    public boolean todayIsHoliday() {
        Holiday holidayNextDay = getHolidayNextDay(cache.get(LocalDate.now()));
        return holidayNextDay != null && holidayNextDay.getHoliday();
    }

    @Override
    public Holiday getToday() {
        return getHolidayNextDay(cache.get(LocalDate.now()));
    }

    @Override
    public Holiday getDay(LocalDate date) {
        return getHolidayNextDay(cache.get(date));
    }

    @Override
    public Holiday getDay(LocalDateTime dateTime) {
        return getHolidayNextDay(cache.get(dateTime.toLocalDate()));
    }

    @Override
    public boolean isWeekend() {
        DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
        return dayOfWeek.equals(DayOfWeek.SUNDAY) || dayOfWeek.equals(DayOfWeek.SATURDAY);
    }

    @Override
    public boolean isWeekend(LocalDate date) {
        DayOfWeek dayOfWeek = date.getDayOfWeek();
        return dayOfWeek.equals(DayOfWeek.SUNDAY) || dayOfWeek.equals(DayOfWeek.SATURDAY);
    }

    /**
     * 获取节假日的下一天放假，并组合起来
     * @param holiday
     * @return
     */
    private Holiday getHolidayNextDay(Holiday holiday) {
        if (holiday == null) {
            return null;
        }
        // 补班
        if (holiday.getHoliday() != null && !holiday.getHoliday()) {
            return holiday;
        }

        LocalDate date = holiday.getDate();
        LinkedList<Holiday> holidays = new LinkedList<>();
        boolean b = true;
        int day = 1;
        while (b) {
            Holiday holiday1 = cache.get(date.plusDays(day++));
            if (holiday1 != null) {
                holidays.add(holiday1);
                continue;
            }
            b = false;
        }

        holiday.setNextDay(holidays);

        return holiday;
    }

}
